<template>
    <div class="my-article">
        <div v-if="loading">加载中...</div>
        <div v-else-if="error">获取文章失败: {{ error }}</div>
        <div v-else>
            <div v-if="!isEditing">
                <ArticleDetail :title="article.title" :content="article.content" />

            </div>
            <div style="height: 100vh;" v-else>
                <ArticleEditor :initialTitle="article.title" :initialContent="article.content"
                    @submit-article="saveArticle" style="height: 100%;" />
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import ArticleDetail from './ArticleDetail.vue';
import ArticleEditor from './ArticleEditor.vue';
import require from '../require';
import { ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';
import { UserStore } from '../store/user';
const userStore = UserStore();

const route = useRoute();
const articleId = ref(route.query.articleId);
const loading = ref(true);
const error = ref(null);
const article = ref({ title: '', content: '' });
const isEditing = ref(false);
const isEditable = ref(true);
const isOk = ref(false);

const fetchArticle = async () => {
    try {
        const res = await require.post('user/findHisArticleById', {
            articleId: articleId.value
        });
        if (res.article.author.userId == userStore.userInfo.userId) {
            isOk.value = true;
        }
        article.value = {
            title: res.article.title,
            content: res.article.content
        };
    } catch (err) {
        error.value = err.message;
    } finally {
        loading.value = false;
    }
};

// 进入编辑模式
const editArticle = () => {
    isEditing.value = true;
};

// 保存修改
const saveArticle = async (articleData) => {
    try {
        const res = await require.post('user/updateArticle', {
            articleId: articleId.value,
            title: articleData.title,
            content: articleData.content
        });
        if ((res !== null) && (res === 200 || (typeof res !== 'number'))) {
            article.value = articleData;
            isEditing.value = false;
            ElMessage.success('文章修改成功');
        }
    } catch (err) {
        ElMessage.error('文章修改失败: ' + err.message);
    }
};

// 取消编辑
const cancelEdit = () => {
    isEditing.value = false;
};

onMounted(fetchArticle);
</script>

<style scoped>
.my-article {
    font-family: Arial, sans-serif;
    padding: 20px;
}
</style>
